package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.config.ChatGptConfig;
import com.erp.gather.domain.*;
import com.erp.gather.domain.bo.ErpCollectProductTranslateTaskBo;
import com.erp.gather.domain.vo.ErpCollectProductTranslateTaskVo;
import com.erp.gather.mapper.*;
import com.erp.gather.service.IErpCollectProductTranslateTaskService;
import com.erp.gather.utils.ChatGptUtils;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.gather.api.domain.ErpCollectProduct;
import com.ruoyi.gather.api.domain.ErpCollectProductExpand;
import com.ruoyi.gather.api.domain.ErpSellerCollectProduct;
import com.ruoyi.gather.api.domain.ErpSellerCollectProductExpand;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 采集商品翻译任务Service业务层处理
 *
 * @author erp
 * @date 2023-04-21
 */
@RequiredArgsConstructor
@Service
public class ErpCollectProductTranslateTaskServiceImpl implements IErpCollectProductTranslateTaskService {

	private final ErpCollectProductTranslateTaskMapper baseMapper;
	private final ErpCollectProductExpandMapper collectProductExpandMapper;
	private final ErpCollectProductMapper erpCollectProductMapper;
	private final ChatGptConfig ChatGptConfig;
	private final ErpSellerCollectProductMapper erpSellerCollectProductMapper;
	private final ErpSellerCollectProductExpandMapper erpSellerCollectProductExpandMapper;

	/**
	 * 查询采集商品翻译任务
	 */
	@Override
	public ErpCollectProductTranslateTaskVo queryById(Long id) {
		return baseMapper.selectVoById(id);
	}

	/**
	 * 查询采集商品翻译任务列表
	 */
	@Override
	public TableDataInfo<ErpCollectProductTranslateTaskVo> queryPageList(ErpCollectProductTranslateTaskBo bo,
																		 PageQuery pageQuery) {
		LambdaQueryWrapper<ErpCollectProductTranslateTask> lqw = buildQueryWrapper(bo);
		Page<ErpCollectProductTranslateTaskVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
		return TableDataInfo.build(result);
	}

	/**
	 * 查询采集商品翻译任务列表
	 */
	@Override
	public List<ErpCollectProductTranslateTaskVo> queryList(ErpCollectProductTranslateTaskBo bo) {
		LambdaQueryWrapper<ErpCollectProductTranslateTask> lqw = buildQueryWrapper(bo);
		return baseMapper.selectVoList(lqw);
	}

	private LambdaQueryWrapper<ErpCollectProductTranslateTask> buildQueryWrapper(ErpCollectProductTranslateTaskBo bo) {
		Map<String, Object> params = bo.getParams();
		LambdaQueryWrapper<ErpCollectProductTranslateTask> lqw = Wrappers.lambdaQuery();
		lqw.eq(bo.getCollectProductId() != null, ErpCollectProductTranslateTask::getCollectProductId,
				bo.getCollectProductId());
		lqw.eq(bo.getStatus() != null, ErpCollectProductTranslateTask::getStatus, bo.getStatus());
		lqw.eq(bo.getAddTime() != null, ErpCollectProductTranslateTask::getAddTime, bo.getAddTime());
		return lqw;
	}

	/**
	 * 新增采集商品翻译任务
	 */
	@Override
	public Boolean insertByBo(ErpCollectProductTranslateTaskBo bo) {
		ErpCollectProductTranslateTask add = BeanUtil.toBean(bo, ErpCollectProductTranslateTask.class);
		validEntityBeforeSave(add);
		boolean flag = baseMapper.insert(add) > 0;
		if (flag) {
			bo.setId(add.getId());
		}
		return flag;
	}

	/**
	 * 修改采集商品翻译任务
	 */
	@Override
	public Boolean updateByBo(ErpCollectProductTranslateTaskBo bo) {
		ErpCollectProductTranslateTask update = BeanUtil.toBean(bo, ErpCollectProductTranslateTask.class);
		validEntityBeforeSave(update);
		return baseMapper.updateById(update) > 0;
	}

	/**
	 * 保存前的数据校验
	 */
	private void validEntityBeforeSave(ErpCollectProductTranslateTask entity) {
		// TODO 做一些数据校验,如唯一约束
	}

	/**
	 * 批量删除采集商品翻译任务
	 */
	@Override
	public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
		if (isValid) {
			// TODO 做一些业务上的校验,判断是否需要校验
		}
		return baseMapper.deleteBatchIds(ids) > 0;
	}

	@Override
	public void save(Long collectProductId, Integer type) {
		
		type = 1;

		// 查看是否已经加入翻译队列
		ErpCollectProductTranslateTask task = baseMapper
				.selectOne(new LambdaQueryWrapper<ErpCollectProductTranslateTask>()
						.eq(ErpCollectProductTranslateTask::getCollectProductId, collectProductId)
						.eq(ErpCollectProductTranslateTask::getType, type));
		if (task == null) {
			task = new ErpCollectProductTranslateTask();
			task.setType(type);
			task.setCollectProductId(collectProductId);
			task.setAddTime(new Date());
			baseMapper.insert(task);

		} else {
			task.setStatus(0);
			baseMapper.updateById(task);
		}

		if (type.equals(1)) {
			// 修改状态
			ErpCollectProductExpand collectProductExpand = collectProductExpandMapper
					.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
							.eq(ErpCollectProductExpand::getCollectProductId, collectProductId));
			collectProductExpand.setIsTranslate(1); // 等待翻译
			collectProductExpandMapper.updateById(collectProductExpand);
		} else {
			ErpSellerCollectProductExpand expand = erpSellerCollectProductExpandMapper
					.selectOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
							.eq(ErpSellerCollectProductExpand::getCollectProductId, collectProductId));
			expand.setIsTranslate(1); // 等待翻译
			erpSellerCollectProductExpandMapper.updateById(expand);
		}
	}

	@Override
	public void refresh(Long collectProductId, Integer type) {
		
		type = 1;
		
		// 修改商品的翻译状态
		if (type.equals(1)) {
			// 修改状态
			ErpCollectProductExpand collectProductExpand = collectProductExpandMapper
					.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
							.eq(ErpCollectProductExpand::getCollectProductId, collectProductId));
			collectProductExpand.setIsTranslate(1); // 等待翻译
			collectProductExpandMapper.updateById(collectProductExpand);
		} else {
			ErpSellerCollectProductExpand expand = erpSellerCollectProductExpandMapper
					.selectOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
							.eq(ErpSellerCollectProductExpand::getCollectProductId, collectProductId));
			expand.setIsTranslate(1); // 等待翻译
			erpSellerCollectProductExpandMapper.updateById(expand);
		}
		// 查看是否已经加入翻译队列
		ErpCollectProductTranslateTask task = baseMapper
				.selectOne(new LambdaQueryWrapper<ErpCollectProductTranslateTask>()
						.eq(ErpCollectProductTranslateTask::getCollectProductId, collectProductId)
						.eq(ErpCollectProductTranslateTask::getType, type));
		if (task == null) {
			task = new ErpCollectProductTranslateTask();
			task.setType(type);
			task.setCollectProductId(collectProductId);
			task.setAddTime(new Date());
			baseMapper.insert(task);
		} else {
			task.setStatus(0);
			baseMapper.updateById(task);
		}
	}

	/**
	 * 翻译
	 */
	@Override
	@Async
	public void translate() {
		// 获取
		LambdaQueryWrapper<ErpCollectProductTranslateTask> lqw = new LambdaQueryWrapper<ErpCollectProductTranslateTask>();
		lqw.eq(ErpCollectProductTranslateTask::getStatus, 0);
		lqw.orderByAsc(ErpCollectProductTranslateTask::getAddTime);
		lqw.last(" limit 1");
		ErpCollectProductTranslateTask task = baseMapper.selectOne(lqw);
		if (task == null)
			return;

		// 判断
		Integer type = task.getType();
		if (type.equals(1)) { // 公共

			task.setStatus(1); // 翻译中
			baseMapper.updateById(task);
			try {

				Long collectProductId = task.getCollectProductId();

				// 获取商品
				ErpCollectProduct collectProduct = erpCollectProductMapper.selectById(collectProductId);

				// 获取扩展类
				ErpCollectProductExpand expand = collectProductExpandMapper
						.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
								.eq(ErpCollectProductExpand::getCollectProductId, collectProductId));

				// 修改任务翻译状态和扩展类的翻译状态
				expand.setIsTranslate(2); // 翻译中
				collectProductExpandMapper.updateById(expand);

				// 翻译逻辑
//		String subject = collectProduct.getSubject(); // 标题
				String customAttributes = collectProduct.getCustomAttributes(); // 属性
//		String detail = collectProduct.getDetail(); // 内容

				String skuProperty = expand.getSkuProperty(); // sku列表
//		String keyword = expand.getKeyword(); // 标题关键字
//		String detailKeyword = expand.getDetailKeyword(); // 详情关键字

				List<Dict> skuList = JsonUtils.parseArrayMap(skuProperty);
				for (Dict dict : skuList) {
					String name = (String) dict.get("name");
					String nameNew = ChatGptUtils.translate(name);
					dict.put("name", nameNew);

					List<HashMap> skuValueList = (List<HashMap>) dict.get("list");
					for (HashMap dict2 : skuValueList) {
						String valueName = (String) dict2.get("name");
						String valueNameNew = ChatGptUtils.translate(valueName);
						dict2.put("name", valueNameNew);
					}
				}
				String skuPropertyNew = JsonUtils.toJsonString(skuList);
				expand.setSkuProperty(skuPropertyNew);
//		expand.setKeyword(ChatGptUtils.translate(keyword));
//		expand.setDetailKeyword(ChatGptUtils.translate(detailKeyword));
				expand.setIsTranslate(3); // 翻译完成
				collectProductExpandMapper.updateById(expand);

//		// 调用翻译接口进行翻译
//		subject = ChatGptUtils.translate(subject);
//		// 判断是否大于128个字符
//		if (subject.length() > 128 || StringUtils.isEmpty(subject)) {
//			String titleKeyWords = expand.getKeyword();
//			// 判断关键词个数，关键词太多也不行
//			if (titleKeyWords.length() > 60) // 超过60，截取
//				while (titleKeyWords.lastIndexOf(",") > 65 || titleKeyWords.length() > 60) {
//					if (titleKeyWords.lastIndexOf(",") < 50)
//						titleKeyWords = titleKeyWords.substring(0, 60);
//					else
//						titleKeyWords = titleKeyWords.substring(0, titleKeyWords.lastIndexOf(","));
//					if (titleKeyWords.length() < 70)
//						break;
//				}
//			subject = ChatGptUtils.createTitle(titleKeyWords); // 根据关键词生成新的128个字符的新标题
//			if (subject.length() > 128 || StringUtils.isEmpty(subject)) {
//				titleKeyWords = titleKeyWords.substring(0, titleKeyWords.lastIndexOf(","));
//				subject = ChatGptUtils.createTitle(titleKeyWords); // 根据关键词生成新的128个字符的新标题
//				if (StringUtils.isEmpty(subject))
//					subject = expand.getKeyword().length() > 128 ? expand.getKeyword().substring(0, 128)
//							: expand.getKeyword();
//			}
//		}
//		collectProduct.setSubject(subject);

				List<Dict> reslist = new ArrayList<Dict>();
				List<Dict> list = JsonUtils.parseArrayMap(customAttributes);
				for (Dict parseMap : list) {
//					String attr_name_id = parseMap.get("attr_name_id") + "";
//					if (attr_name_id.equals("-1"))
//						continue;

					Object attr_value_id = parseMap.get("attr_value_id");
					Object attr_value_ = parseMap.get("attr_value");
					if (attr_value_id == null && attr_value_ == null)
						continue;
					if (attr_value_id != null && attr_value_id.toString().contains("[]"))
						continue;
					if (attr_value_id != null && attr_value_id.toString().isEmpty())
						continue;

					String attr_name = (String) parseMap.get("attr_name");
					String attr_value = (String) parseMap.get("attr_value");
					String attr_name_new = ChatGptUtils.translate(attr_name);
					parseMap.put("attr_name", attr_name_new);
					String attr_value_new = ChatGptUtils.translate(attr_value);
					parseMap.put("attr_value", attr_value_new);
					reslist.add(parseMap);
				}
				String customAttributesNew = JsonUtils.toJsonString(reslist);

				collectProduct.setCustomAttributes(customAttributesNew);

//		detail = ChatGptUtils.translate(detail);
//		if (StringUtils.isEmpty(detail)) { // 如果翻译的详情为空说明有问题，需要重新生成详情
//			detail = ChatGptUtils.createProductDescription(expand.getDetailKeyword());
//			if (StringUtils.isEmpty(detail))
//				detail = expand.getDetailKeyword();
//		}
//		collectProduct.setDetail(detail);
				erpCollectProductMapper.updateById(collectProduct);

				task.setStatus(2); // 翻译中
			} catch (Exception e) {
				e.printStackTrace();
				task.setStatus(3); // 翻译失败
			}
			baseMapper.updateById(task);
		} else if (type.equals(2)) {
			task.setStatus(1); // 翻译中
			baseMapper.updateById(task);
			try {

				Long collectProductId = task.getCollectProductId();

				// 获取商品
				ErpSellerCollectProduct collectProduct = erpSellerCollectProductMapper.selectById(collectProductId);

				// 获取扩展类
				ErpSellerCollectProductExpand expand = erpSellerCollectProductExpandMapper
						.selectOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
								.eq(ErpSellerCollectProductExpand::getCollectProductId, collectProductId));

				// 修改任务翻译状态和扩展类的翻译状态
				expand.setIsTranslate(2); // 翻译中
				erpSellerCollectProductExpandMapper.updateById(expand);

				// 翻译逻辑
				String customAttributes = collectProduct.getCustomAttributes(); // 属性

				String skuProperty = expand.getSkuProperty(); // sku列表

				List<Dict> skuList = JsonUtils.parseArrayMap(skuProperty);
				for (Dict dict : skuList) {
					String name = (String) dict.get("name");
					String nameNew = ChatGptUtils.translate(name);
					dict.put("name", nameNew);

					List<HashMap> skuValueList = (List<HashMap>) dict.get("list");
					for (HashMap dict2 : skuValueList) {
						String valueName = (String) dict2.get("name");
						String valueNameNew = ChatGptUtils.translate(valueName);
						dict2.put("name", valueNameNew);
					}
				}
				String skuPropertyNew = JsonUtils.toJsonString(skuList);
				expand.setSkuProperty(skuPropertyNew);
				expand.setIsTranslate(3); // 翻译完成
				erpSellerCollectProductExpandMapper.updateById(expand);

				List<Dict> reslist = new ArrayList<Dict>();
				List<Dict> list = JsonUtils.parseArrayMap(customAttributes);
				for (Dict parseMap : list) {
//					String attr_name_id = parseMap.get("attr_name_id") + "";
//					if (attr_name_id.equals("-1"))
//						continue;

					Object attr_value_id = parseMap.get("attr_value_id");
					Object attr_value_ = parseMap.get("attr_value");
					if (attr_value_id == null && attr_value_ == null)
						continue;
					if (attr_value_id != null && attr_value_id.toString().contains("[]"))
						continue;
					if (attr_value_id != null && attr_value_id.toString().isEmpty())
						continue;

					String attr_name = (String) parseMap.get("attr_name");
					String attr_value = (String) parseMap.get("attr_value");
					String attr_name_new = ChatGptUtils.translate(attr_name);
					parseMap.put("attr_name", attr_name_new);
					String attr_value_new = ChatGptUtils.translate(attr_value);
					parseMap.put("attr_value", attr_value_new);
					reslist.add(parseMap);
				}
				String customAttributesNew = JsonUtils.toJsonString(reslist);

				collectProduct.setCustomAttributes(customAttributesNew);

				erpSellerCollectProductMapper.updateById(collectProduct);

				task.setStatus(2); // 翻译中
			} catch (Exception e) {
				e.printStackTrace();
				task.setStatus(3); // 翻译失败
			}
			baseMapper.updateById(task);
		}
	}

}
